<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        style="width: 200px;"
        class="filter-item"
        placeholder="模板名称"
        v-model="queryForm.name"
      >
      </el-input>
      <el-input
        style="width: 200px;"
        class="filter-item"
        placeholder="生产厂家"
        v-model="queryForm.factoryId"
      >
      </el-input>
      <el-input
        style="width: 200px;"
        class="filter-item"
        placeholder="型号"
        v-model="queryForm.modelId"
      >
      </el-input>
      <el-button
        class="filter-item"
        v-permission="'batteryModule:search'"
        @click="doSearchQuery"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-search"
        >查询</el-button
      >
      <el-button
        v-permission="'batteryTemp:add'"
        class="filter-item"
        style="margin-left: 10px;"
        @click="openCreateDialog"
        type="success"
        icon="el-icon-plus"
        >新增</el-button
      >
    </div>
    <el-table
      v-loading="loading"
      @sort-change="handleSortChange"
      :data="records"
      style="width: 100%"
    >
      <el-table-column prop="name" label="模板名称" width="220" align="center">
      </el-table-column>
      <el-table-column prop="code" label="模板编号" width="150" align="center">
      </el-table-column>
      <el-table-column
        prop="bussinessId"
        label="所属企业"
        width="150"
        align="center"
      >
      </el-table-column>
      <el-table-column prop="type" label="电池类型" width="130" align="center">
        <template slot-scope="scope">
          {{ Dicts.BATTERY_TYPE[scope.row.type] }}
        </template>
      </el-table-column>
      <el-table-column
        prop="volume"
        label="标称容量"
        width="130"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="energy"
        label="标称能量"
        width="130"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="cutoffPowerIn"
        label="充电截止电压"
        width="150"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="cutoffPowerOut"
        label="放电截止电压"
        width="150"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="factoryName"
        label="生产厂家"
        width="100"
        align="center"
      >
      </el-table-column>
      <el-table-column prop="modelName" label="型号" width="200" align="center">
      </el-table-column>
      <el-table-column
        align="center"
        label="操作"
        class-name="small-padding"
        fixed="right"
        width="150"
      >
        <template slot-scope="scope">
          <el-button
            v-permission="'batteryTemp:detail'"
            size="mini"
            type="success"
            @click="TemplateDetails(scope.row.rowId)"
            title="详情"
            icon="el-icon-tickets"
            circle
          ></el-button>
          <el-button
            v-permission="'batteryTemp:detail'"
            size="mini"
            type="primary"
            @click="TempDownload(scope.row.rowId)"
            title="下载模板"
            icon="el-icon-download"
            circle
          ></el-button>
          <el-button
            v-permission="'batteryTemp:delete'"
            size="mini"
            type="danger"
            @click="handleDelete(scope.row.rowId)"
            title="删除"
            icon="el-icon-delete"
            circle
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryForm.current"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="queryForm.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="queryForm.total"
      >
      </el-pagination>
    </div>
    <el-dialog
      title="新增模板"
      :visible.sync="dialogAddFormVisible"
      width="50%"
    >
      <el-form
        :model="addForm"
        label-width="160px"
        :rules="addFormRules"
        ref="addForm"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="生产厂家:" prop="factoryName">
              <el-autocomplete
                class="inline-input"
                v-model="addForm.factoryName"
                @select="queryTemp"
                @blur="queryTemp"
                :fetch-suggestions="querySearch1"
                placeholder="生产厂家"
                style="width:300px"
              ></el-autocomplete>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="型号:" prop="modelName">
              <el-autocomplete
                class="inline-input"
                v-model="addForm.modelName"
                @select="getFactoryModel"
                @focus="getFactoryModel"
                @blur="getFactoryModel"
                :fetch-suggestions="querySearch3"
                style="width:300px"
                placeholder="型号"
              ></el-autocomplete>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="模板名称:" prop="name">
              <el-input
                v-model="addForm.name"
                placeholder="模板名称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电池类型:">
              <el-select
                v-model="addForm.type"
                placeholder="可选电池类型"
                style="width: 100%;"
              >
                <el-option
                  v-for="(val, key) in Dicts.BATTERY_TYPE"
                  :key="key"
                  :label="val"
                  :value="key"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="标称容量:" prop="volume">
              <el-input
                v-model="addForm.volume"
                placeholder="标称容量"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="标称能量:" prop="energy">
              <el-input
                v-model="addForm.energy"
                placeholder="标称能量"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="充电截止电压:" prop="cutoffPowerIn">
              <el-input
                v-model="addForm.cutoffPowerIn"
                placeholder="充电截止电压"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="放电截止电压:" prop="cutoffPowerOut">
              <el-input
                v-model="addForm.cutoffPowerOut"
                placeholder="放电截止电压"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogAddFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveAddForm">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="模板详情"
      :visible.sync="dialogDetailsFormVisible"
      width="50%"
    >
      <el-form :model="detailForm" label-width="160px" ref="detailForm">
        <el-row>
          <el-col :span="12">
            <el-form-item label="模板编号:" prop="code">
              {{ detailForm.code }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模板名称:" prop="name">
              {{ detailForm.name }}
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="所属企业:" prop="bussinessId">
              {{ detailForm.bussinessId }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="标称容量:" prop="volume">
              {{ detailForm.volume }}
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="标称能量:" prop="energy">
              {{ detailForm.energy }}
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="标称能量:" prop="energy">
              {{ detailForm.energy }}
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="充电截止电压:" prop="cutoffPowerIn">
              {{ detailForm.cutoffPowerIn }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="放电截止电压:" prop="cutoffPowerOut">
              {{ detailForm.cutoffPowerOut }}
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="closeDialogDetails">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  queryBatteryTemp,
  addBatteryTemp,
  queryBatteryTempDetail,
  deleteBatteryTemp,
  getFactory,
  getFactoryModel,
  explodBatteryTemp
} from '@/api/battery'
// import FileSaver from 'file-saver'
import toExcel from '@/excel/json2excel'
export default {
  name: 'Batterytemp',
  data() {
    var checkVolume = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入标称容量'))
      }
      if (!/^[0-9]*$/.test(value)) {
        callback(new Error('只能输入数字'))
      } else {
        callback()
      }
    }
    var checkEnergy = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入标称能量'))
      }
      if (!/^[0-9]*$/.test(value)) {
        callback(new Error('只能输入数字'))
      } else {
        callback()
      }
    }
    var checkCutoffPowerIn = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入充电截止电压'))
      }
      if (!/^[0-9]*$/.test(value)) {
        callback(new Error('只能输入数字'))
      } else {
        callback()
      }
    }
    var checkCutoffPowerOut = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入放电截止电压'))
      }
      if (!/^[0-9]*$/.test(value)) {
        callback(new Error('只能输入数字'))
      } else {
        callback()
      }
    }
    return {
      dialogFormVisible: false,
      dialogAddFormVisible: false,
      dialogDetailsFormVisible: false,
      deletedialogFormVisible: false,
      loading: false,
      addForm: {
        factoryName: '',
        name: '',
        volume: '',
        energy: '',
        cutoffPowerIn: '',
        cutoffPowerOut: '',
        factoryId: '',
        type: '',
        modelId: ''
      },

      addFormRules: {
        factoryName: [
          { required: true, message: '请输入生产厂家', trigger: 'blur' }
        ],
        modelName: [{ required: true, message: '请输入型号', trigger: 'blur' }],
        name: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
        type: [{ required: true, message: '请选择电池类型', trigger: 'blur' }],
        volume: [{ required: true, validator: checkVolume, trigger: 'blur' }],
        energy: [{ required: true, validator: checkEnergy, trigger: 'blur' }],
        cutoffPowerIn: [
          { required: true, validator: checkCutoffPowerIn, trigger: 'blur' }
        ],
        cutoffPowerOut: [
          { required: true, validator: checkCutoffPowerOut, trigger: 'blur' }
        ]
      },
      records: [],
      queryForm: {
        current: 1,
        pages: 0,
        total: 0,
        size: 10,
        name: '',
        factoryId: '',
        modelId: ''
      },
      detailForm: {
        rowId: 0,
        bussinessId: '',
        code: 0,
        name: '',
        volume: 0,
        energy: 0,
        cutoffPowerIn: 0,
        cutoffPowerOut: 0,
        factoryId: '',
        type: '',
        model: ''
      },
      deleteForm: {
        name: '',
        volume: '',
        energy: '',
        cutoffPowerIn: '',
        cutoffPowerOut: '',
        factoryId: '',
        type: '',
        modelId: ''
      },
      qr: { qrCode: null },
      restaurantsList: {
        name: [],
        volume: [],
        energy: [],
        cutoffPowerIn: [],
        cutoffPowerOut: [],
        factoryId: [],
        type: [],
        modelId: []
      },
      list: [],
      restaurants: {},
      tempList: [],
      factoryList: [],
      restaurantsFac: {
        name: []
      },
      FactoryMode: '',
      excelData: [
        { name: '张三', birthday: new Date('1990-01-01'), sex: '男', age: 28 },
        { name: '李四', birthday: new Date('1991-01-01'), sex: '女', age: 27 }
      ]
    }
  },
  created() {
    this.doQuery()
  },

  methods: {
    querySearch1(queryString, cb) {
      var restaurants = this.restaurantsFac.factoryName
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    querySearch3(queryString, cb) {
      var restaurants = this.restaurantsList.modelName
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)
    },

    createFilter(queryString) {
      return restaurant => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        )
      }
    },

    doSearchQuery() {
      this.queryForm.current = 1
      this.doQuery()
    },
    // 渲染页面
    doQuery() {
      this.loading = true
      queryBatteryTemp(this.queryForm).then(({ data: { data } }) => {
        //  console.log('设备所有数据', data)
        this.queryForm.current = data.current
        this.queryForm.pages = data.pages
        this.queryForm.total = data.total
        this.queryForm.size = data.size
        this.records = data.records
        this.loading = false
      })
    },
    // 打开新增模板弹窗
    openCreateDialog() {
      this.addForm = {
        factoryName: '',
        factoryId: '',
        modelName: '',
        modelId: '',
        name: '',
        volume: '',
        energy: '',
        cutoffPowerIn: '',
        cutoffPowerOut: '',
        type: ''
      }
      this.FactoryMode = ''
      this.queryTemp()
      this.dialogAddFormVisible = true
      this.$refs.addForm && this.$refs.addForm.resetFields()
    },

    queryTemp() {
      getFactory().then(({ data: { data } }) => {
        this.factoryList = data
        // console.log('获取厂家', this.factoryList)
        this.factoryListForEach()
      })
    },
    factoryListForEach() {
      this.restaurantsFac = {
        factoryName: []
      }
      this.factoryList.forEach((item, index) => {
        this.restaurantsFac.factoryName[index] = { value: item.name }
      })
      for (var k = 0, length = this.factoryList.length; k < length; k++) {
        if (this.addForm.factoryName === this.factoryList[k].name) {
          this.addForm.factoryId = this.factoryList[k].rowId
          this.FactoryMode = this.factoryList[k].rowId
          return
        } else {
          this.addForm.factoryId = ''
        }
      }
    },

    getFactoryModel() {
      getFactoryModel(this.FactoryMode).then(({ data: { data } }) => {
        this.FactoryModelList = data
        // console.log('型号', this.tempList)
        this.FactoryModelforEach()
      })
    },

    FactoryModelforEach() {
      this.restaurantsList = {
        modelName: []
      }
      this.FactoryModelList.forEach((item, index) => {
        this.restaurantsList.modelName[index] = { value: item.name }
      })
      for (var k = 0, length = this.FactoryModelList.length; k < length; k++) {
        if (this.addForm.modelName === this.FactoryModelList[k].name) {
          this.addForm.modelId = this.FactoryModelList[k].rowId
          return
        } else {
          this.addForm.modelId = ''
        }
      }
    },

    // 提交新增表单
    saveAddForm() {
      // console.log(this.addForm)
      this.$refs.addForm.validate(valid => {
        if (valid) {
          // console.log("提交的额添加参数", this.addForm)
          this.$confirm('请确定模板信息正确?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            addBatteryTemp(this.addForm)
              .then(({ data: { data, msg, code } }) => {
                // console.log("请求到的模板", data)
                this.doQuery()
                this.dialogAddFormVisible = false
                this.$message({
                  showClose: true,
                  message: msg,
                  type: '模板添加成功'
                })
              })
              .catch(_ => {
                this.loading = false
              })
          })
        } else {
          return false
        }
      })
    },

    // 重新排序
    handleSortChange({ column, prop, order }) {
      this.queryForm.ascs = ''
      this.queryForm.descs = ''
      if (order) {
        if (order === 'ascending') {
          this.queryForm.ascs = column.sortBy
        } else {
          this.queryForm.descs = column.sortBy
        }
      }
      this.queryForm.current = 0
      this.doQuery()
    },
    // 分页器
    handleCurrentChange(current) {
      this.queryForm.current = current
      this.doQuery()
    },
    // 分页器
    handleSizeChange(size) {
      this.queryForm.size = size
      this.doQuery()
    },
    // 模板详情
    TemplateDetails(rowId) {
      this.dialogDetailsFormVisible = true
      this.loading = true
      // console.log(rowId)
      queryBatteryTempDetail(rowId).then(({ data: { code, data, msg } }) => {
        // console.log(data)
        this.loading = false
        if (code === 0) {
          this.detailForm = {
            rowId: data.rowId,
            bussinessId: data.bussinessId,
            code: data.code,
            name: data.name,
            volume: data.volume,
            energy: data.energy,
            cutoffPowerIn: data.cutoffPowerIn,
            cutoffPowerOut: data.cutoffPowerOut,
            factoryId: data.factoryId,
            type: data.type,
            model: data.model
          }
        }
      })
    },
    closeDialogDetails() {
      this.dialogDetailsFormVisible = false
      this.detailForm = {}
    },
    // 删除
    handleDelete(rowId) {
      this.$confirm('此操作将永久删除该示例, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        deleteBatteryTemp(rowId).then(({ data: { data, msg } }) => {
          this.loading = false
          this.doQuery()
          this.$message({
            showClose: true,
            message: msg,
            type: 'success'
          })
        })
      })
    },
    // 下载模板
    TempDownload(rowId) {
      explodBatteryTemp(rowId).then(({ data: { data, msg } }) => {
        // console.log('请求到的模板', data)
        // const th = ['模板名称','模板编号', '生产厂家', '型号', '电池类型', '标称容量', '标称能量', '充电截至电压', '放电截至电压','模组编号', '外观','所属项目', 'DCR', '初始电压', '初始正极绝缘', '初始负极绝缘', '初始充电能量', '初始放电能量', '初始充电电容', '初始放电电容']
        // const filterVal = ['tempName','batteryTempCode', 'factoryName', 'model', 'type', 'volume', 'energy', 'cutoffPowerIn', 'cutoffPowerOut', 'code','appearance','projectName',  'dcr', 'firstVolt', 'firstRightInsulation', 'firstNegativeInsulation', 'firstEnergyOut', 'firstEnergyIn', 'firstCapacityIn', 'firstCapacityOut']
        const th = data.title
        const filterVal = data.value
        this.excelData = [
          {
            tempName: data.content[0],
            batteryTempCode: data.content[1],
            factoryName: data.content[2],
            model: data.content[3],
            type: data.content[4],
            volume: data.content[5],
            energy: data.content[6],
            cutoffPowerIn: data.content[7],
            cutoffPowerOut: data.content[8],

            code: '',
            appearance: '',
            projectName: '',
            dcr: '',
            firstVolt: '',
            firstRightInsulation: '',
            firstNegativeInsulation: '',
            firstEnergyOut: '',
            firstEnergyIn: '',
            firstCapacityIn: '',
            firstCapacityOut: ''
          }
        ]
        const data1 = this.excelData.map(v => filterVal.map(k => v[k]))
        const [fileName, fileType, sheetName] = [
          data.fileName,
          data.fileType,
          data.sheetName
        ]
        toExcel({ th, data1, fileName, fileType, sheetName })
      })
    }
  }
}
</script>

<style scoped lang="scss">
.button_name {
  width: 80px;
  height: 30px;
  background-color: #67c23a;
  font-size: 15px;
  border-radius: 4px;
  color: white;
  border: none;
  outline: none;
  text-align: center;
  text-decoration: none;
  display: inline-block;
}
.button_name {
  -webkit-transition-duration: 0.2s; /* Safari */
  transition-duration: 0.2s;
}
.button_name:hover {
  background-color: #85ce61; /* Green */
  color: white;
}
.device-status {
  width: 8px;
  height: 8px;
  margin-right: 3px;
  border-radius: 50%;
  display: inline-block;
  background: #a7a7a7;
  &.online {
    background: green;
  }
  &.offline {
    background: red;
  }
  &.sleep {
    background: gray;
  }
}
.detaileTitle {
  font-size: 18px;
  float: left;
  margin-left: 10px;
}
.detaileData {
  font-size: 18px;
  float: right;
  margin-right: 140px;
  color: #409eff;
}
.detaileCol {
  margin-bottom: 10px;
}
</style>
